package net.dgi.common.match.impl;

import net.dgi.common.ioc.Inject;
import net.dgi.common.ioc.InjectSource;
import net.dgi.common.ioc.Injector;

/**
 * Viva IntelliJ IDEA.
 * User: Deian Date: Sep 30, 2010 Time: 10:17:43 PM
 */
public class MatchExecutor implements Runnable {
    @Inject(InjectSource.SHARE)
    protected MatchContext context;

    @Inject(InjectSource.SHARE)
    protected FunctionRegistry functionRegistry;

    public MatchExecutor() {
        Injector.inject(this);
    }

    public void run() {
        for(;;) {
            if (context.hasShutdownSignal) {
                return;
            }
            MatchAssignment task = context.executionQueue.poll();
            try {
                if (task == null) {
                    wait();
                }
                Function function = task.getFunction();
                MatchRequest request = task.getMatchRequest();
                Object data = request.getData();
                Object result = function.method.invoke(function.instance, new Object[] {data});
                if (result != null) {
                    context.incomingQueue.add(new MatchRequest(result, request.getPassCount() + 1, request.getOriginationTime()));
                }
            } catch (InterruptedException e) {
                continue;
            } catch (Throwable t) {
                context.outgoingQueue.add(new MatchResult(task, t));
            }
        }
    }
}
